// token相关模块
const jwt = require("jsonwebtoken")
const moment = require('moment')
const errcode = require(__util + "/errcode")

const secret = process.env.TOKEN_SECRET


// 签发token
const signToken = async (account) => {
  const option = {
    iat: moment().unix(),
    exp: moment().add(1, 'days').unix()
  }
  if (account) {
    option.account = account
  }

  return await jwt.sign(option, secret)
}

// 验证token
const verifyToken = async (option) => {
  let { token } = option

  return await jwt.verify(token, secret)
}

// 路由拦截中间件, 检测token
const intercept = () => {
  return async (req, res, next) => {
    let token;
    if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
      token = req.headers.authorization.split(' ')[1];
    }

    if (token) {
      try {
        const { account } = await verifyToken({ token: token })
        req.account = account  // 将解析出来的用户信息附带在请求中, 方便后续代码直接取用
        next()
      } catch (err) {
        switch (err.name) {
          case "JsonWebTokenError":
            return res.json(errcode.TOKEN_INVALID)
          case "TokenExpiredError":
            return res.json(errcode.TOKEN_EXPIRED)
          case "NotBeforeError":
            return res.json(errcode.TOKEN_INACTIVE)
          default:
            return res.json(errcode.TOKEN_INVALID)
        }
      }
    }
    else {
      return res.json(errcode.NO_PERMISSION)
    }
  }
}

module.exports = {
  signToken: signToken,
  verifyToken: verifyToken,
  intercept: intercept
}